import pandas as pd
import numpy as np
from toolsSrc.files.checkFiles import checkCsvFiles
from common.config import yawConfig as Config
from toolsSrc.dbtools.getDBData import getWindSpeedFromDBData1


''' CALL BACK  改用下面的函数，这个现在不用了  #######################################################
1. 从Config.data1File文件 中读取当前风速
2. 在 Config.onlLineRegress文件 中查找风速最接近的 windDirection
3. 将 {‘WindDirOffset’:[windDirection]} 写入Config.yawUpload文件
'''
# @timeit
def toYawUploadCsv_byData1File():

    if checkCsvFiles([Config.data1File, Config.onlLineRegress]) is False:
        return

    df_data1File = pd.read_csv(Config.data1File)
    df_onlLineRegress = pd.read_csv(Config.onlLineRegress)
    windSpeed = df_data1File.loc[0, Config.WindSpeed]

    WindSpeed_new = np.array(abs(df_onlLineRegress[Config.WindSpeed] - windSpeed))
    min = np.min(WindSpeed_new)
    indexMin = np.argmin(WindSpeed_new)
    if min > 1: return  # 如果最小偏差都很大，不进行后面的上传操作
    df_yawUpload = pd.DataFrame({Config.yawPlcKey: [df_onlLineRegress.loc[indexMin, Config.WindDirection]]})
    print("当前风速：",windSpeed,Config.yawPlcKey, "：",df_yawUpload.iloc[0,0])
    df_yawUpload.to_csv(Config.YawUpload, index=False)


''' CALL BACK #######################################################
1. 从数据库data1表中读取当前风速
2. 在 Config.onlLineRegress文件 中查找风速最接近的 windDirection
3. 将 {‘WindDirOffset’:[windDirection]} 写入Config.yawUpload文件
'''
def toYawUploadCsv():

    if checkCsvFiles([Config.onlLineRegress]) is False:
        return

    windSpeed = getWindSpeedFromDBData1()
    df_onlLineRegress = pd.read_csv(Config.onlLineRegress)

    WindSpeed_new = np.array(abs(df_onlLineRegress[Config.WindSpeed] - windSpeed))
    min = np.min(WindSpeed_new)
    indexMin = np.argmin(WindSpeed_new)
    if min > 1: return  # 如果最小偏差都很大，不进行后面的上传操作
    df_yawUpload = pd.DataFrame({Config.yawPlcKey: [df_onlLineRegress.loc[indexMin, Config.WindDirection]]})
    print("当前风速：",windSpeed,Config.yawPlcKey, "：",df_yawUpload.iloc[0,0])
    df_yawUpload.to_csv(Config.YawUpload, index=False)